package apollo.generator.modules.service.impl;

import apollo.generator.common.exception.CustomException;
import apollo.generator.common.utils.*;
import apollo.generator.modules.dao.DataBaseConfigDao;
import apollo.generator.modules.entity.DataBaseConfigEntity;
import apollo.generator.modules.enums.EnableEnum;
import apollo.generator.modules.service.DataBaseConfigService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * <Description>
 * 数据库配置
 * @author Jun Lee
 * @email tommy2015yoyo@163.com
 * @createDate 2020-07-02 10:21:00
 */
@Service("dataBaseConfigService")
public class DataBaseConfigServiceImpl extends ServiceImpl<DataBaseConfigDao, DataBaseConfigEntity> implements DataBaseConfigService {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) throws CustomException {
        IPage<DataBaseConfigEntity> page = this.page(
                new Query<DataBaseConfigEntity>().getPage(params),
                new QueryWrapper<DataBaseConfigEntity>().select(DataBaseConfigEntity.class,info -> !info.getColumn().equals("password"))
                .eq("create_user_id",LoginUtils.getUserId())
        );

        return new PageUtils(page);
    }

    @Override
    public void enable(Long id, Integer enable, Long userId) {
        //禁用所有数据库
        UpdateWrapper<DataBaseConfigEntity> wrapper = new UpdateWrapper<>();
        if (EnableEnum.ENABLE.getCode().equals(enable)) {
            wrapper.eq("create_user_id",userId).set("is_enable",EnableEnum.DISABLE.getCode());
            update(wrapper);
        }
        //启用当前数据库
        wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id).set("is_enable",enable);
        //获取被启用的数据库信息,存入redis中
        DataBaseConfigEntity entity = getById(id);
        redisUtils.set(RedisKeys.getSysDataBaseConfigKey(LoginUtils.getUserId()), JSON.toJSONString(entity),RedisUtils.NOT_EXPIRE);
        update(wrapper);
    }

    @Override
    public DataBaseConfigEntity selectEnableDataBase() throws CustomException {
        QueryWrapper<DataBaseConfigEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("create_user_id", LoginUtils.getUserId()).eq("is_enable",EnableEnum.ENABLE.getCode());
        DataBaseConfigEntity one = getOne(wrapper);
        if (StringUtils.isEmpty(one)) {
            CustomException.throwCustomException("找不到启用的数据库配置");
        }
        redisUtils.set(RedisKeys.getSysDataBaseConfigKey(LoginUtils.getUserId()), JSON.toJSONString(one),RedisUtils.NOT_EXPIRE);
        return one;
    }
}